import axios from 'axios';

// 创建axios实例
const instance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000
});

// 请求拦截器
instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }
        return Promise.reject(error);
    }
);

/**
 * 获取角色列表
 */
const getCharacters = () => {
    return instance.get('/user/ai/characters');
};

/**
 * 搜索角色
 */
const searchCharacters = (keyword) => {
    return instance.get(`/user/ai/characters/search?keyword=${encodeURIComponent(keyword)}`);
};

// 获取角色详情
const getCharacterByRoleKey = async (roleKey) => {
    try {
        // 使用instance而不是request
        const response = await instance.get(`/user/ai/characters/${roleKey}`);
        return response;
    } catch (error) {
        console.error('获取角色详情失败:', error);
        throw error;
    }
};

export {
    getCharacters,
    searchCharacters,
    getCharacterByRoleKey
};